----------------------------------------------------------------------------------
-- Company: 
-- Engineer: 
-- 
-- Create Date:    10:42:41 06/02/2010 
-- Design Name: 
-- Module Name:    Average_Filter - Behavioral 
-- Project Name: 
-- Target Devices: 
-- Tool versions: 
-- Description: 
--
-- Dependencies: 
--
-- Revision: 
-- Revision 0.01 - File Created
-- Additional Comments: 
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

---- Uncomment the following library declaration if instantiating
---- any Xilinx primitives in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity Average_Filter is
    Port ( Data_in : in  STD_LOGIC_VECTOR (11 downto 0);
           Data_out : out  STD_LOGIC_VECTOR (11 downto 0);
           reset : in  STD_LOGIC;
           divider : in  STD_LOGIC_VECTOR (7 downto 0);
			  newdata_in : in STD_LOGIC;
			  newdata_out : out STD_LOGIC := '0');
end Average_Filter;

architecture Behavioral of Average_Filter is
signal Data_avg : STD_LOGIC_VECTOR (35 downto 0) := "000000000000000000000000000000000000";
signal counter : STD_LOGIC_VECTOR (23 downto 0) := "000000000000000000000000";
signal n : STD_LOGIC_VECTOR (23 downto 0) := "000000000000000000000000";
signal newdata_intern : STD_LOGIC := '0';
begin
P1: process(newdata_in, reset)
variable newdata_inPos : STD_LOGIC := '0';
begin
   
if reset = '1' then
	Data_avg <= "000000000000000000000000000000000000";
--	Data_out <= "000000000000";
	counter <= "000000000000000000000000";
	n <= "000000000000000000000000";	
  
elsif newdata_in='1' and newdata_inPos='0' then --rising edge

	if(divider = "00000000")then
		Data_avg(11 downto 0) <= Data_in;
		
		newdata_intern <= '1';
		counter <=  "000000000000000000000000";
	else
			if(counter =  "000000000000000000000000") then
					Data_avg <= "000000000000000000000000"&Data_in;
					
					counter <= counter + 1;
					n(conv_integer(divider)) <= '1'; 
			elsif(counter < (n-1)) then
					Data_avg <= Data_avg + Data_in;
					counter <= counter + 1;
			else
					counter <= "000000000000000000000000";
					Data_avg <= Data_avg + Data_in;
					--Data_out <= Data_avg(conv_integer(divider)+11 downto conv_integer(divider));
					newdata_intern <= '1';
			end if;	
		newdata_inPos := '1'	;		
	end if;
elsif newdata_in='0' then  
	newdata_intern <= '0';
	newdata_inPos := '0';
end if;

end process;

P2: process(newdata_intern)
variable newdata_internPos : STD_LOGIC := '0';
begin
	if newdata_intern='1' and newdata_internPos='0' then --rising edge
		Data_out <= Data_avg(conv_integer(divider)+11 downto conv_integer(divider));
		newdata_out <= '1';
		newdata_internPos := '1';
	else
		newdata_out <= '0';
		newdata_internPos := '0';
	end if;

end process;
end Behavioral;

